package com.cn.medicalcare.service.serviceimpl;

import com.cn.medicalcare.customtool.JedisUtil;
import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.Admin;
import com.cn.medicalcare.service.LoginService;

import java.util.LinkedHashMap;
import java.util.Map;

public class LoginServiceImpl implements LoginService {

    public static final String TOKEN = "backstage_";

    public static final int TOKEN_TIME = 30 * 60;

    //静态内部类单例模式
    private static class SingletonClassInstance {
        private static final LoginServiceImpl instance = new LoginServiceImpl();
    }

    private LoginServiceImpl() {
    }

    public static LoginServiceImpl getInstance() {
        return LoginServiceImpl.SingletonClassInstance.instance;
    }


    private AdminServiceImpl adminService = AdminServiceImpl.getInstance();

    @Override
    public Map<String, Object> isLogin(String username, String password) {
        Admin admin = adminService.selectAdminByUsername(username);
        Map<String, Object> map = new LinkedHashMap<>();
        if (admin == null) {
            //用户名不存在
            map.put("status", 404);
            map.put("message", "用户名不存在");
            return map;
        }
        if (admin.getSurvival() == 0) {
            //用户未激活
            map.put("status", 404);
            map.put("message", "用户名未激活");
            return map;
        }
        if (!admin.getPassword().equals(adminService.encryption(password))) {
            //密码错误
            map.put("status", 404);
            map.put("message", "密码错误");
            return map;
        }
        //密码验证通过
        map.put("status", 200);
        String token = TOKEN + username;
        String adminJson = JsonTool.toJson(admin);
        JedisUtil.jedisDo(j -> {
            j.select(15);
            return  j.setex(token, TOKEN_TIME,adminJson);
        });
        map.put("sessionId", token);
        return map;
    }
}
